package com.gm.commonlib.views.timePickerView;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.github.gzuliyujiang.calendarpicker.CalendarPicker;
import com.github.gzuliyujiang.calendarpicker.core.ColorScheme;
import com.github.gzuliyujiang.calendarpicker.core.DateUtils;
import com.gm.commonlib.R;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.commonlib.views.timePickerView.builder.TimePickerBuilder;
import com.gm.commonlib.views.timePickerView.listener.OnTimeSelectListener;
import com.gm.commonlib.views.timePickerView.view.TimePickerView;
import com.gm.commonlib.views.toast.ToastUtil;

import java.util.Calendar;
import java.util.Date;

public class TimePickerViewUtils {

    //todo 测试代码
    private void test(Context context) {
        Calendar startDate = Calendar.getInstance();
        startDate.set(2014, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        TimePickerViewUtils.showTimeByYMD(context, startDate, endDate, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                ToastUtil.showToast("时间: " + DateTimeUtils.getTimeForData(date));
            }
        });
    }

    /**
     * 显示 年月日的 时间控件
     *
     * @param context
     * @param startRangDate  时间限制范围开始时间
     * @param endRangDate    时间限制范围结束时间（这个时间以后的时间不显示）
     * @param selectListener 时间选中回调
     */


    public static TimePickerView showTimeByYMD(Context context, Calendar startRangDate, Calendar endRangDate, OnTimeSelectListener selectListener) {
        boolean[] type = new boolean[]{true, true, true, false, false, false};
        return show(context, null, type, startRangDate, endRangDate, null, selectListener, null);
    }


    public static TimePickerView showTimeByYMD(Context context, String title, Long selectTime, OnTimeSelectListener selectListener) {
        boolean[] type = new boolean[]{true, true, true, false, false, false};
        return show(context, title, type, null, null, selectTime, selectListener, null);
    }

    public static TimePickerView showTimeByYMD(Context context, String title, Long selectTime, OnTimeSelectListener selectListener,
                                               View.OnClickListener cancelClickListener) {
        boolean[] type = new boolean[]{true, true, true, false, false, false};
        return show(context, title, type, null, null, selectTime, selectListener, cancelClickListener);
    }


    /**
     * 显示 年月日时分的 时间控件
     *
     * @param context
     */


    public static TimePickerView showTimeByYMDH(Context context, String title, Long selectTime, OnTimeSelectListener selectListener) {
        boolean[] type = new boolean[]{true, true, true, true, false, false};
        return show(context, title, type, null, null, selectTime, selectListener, null);
    }

    public static TimePickerView showTimeByYMDH(Context context, String title, Calendar startRangDate, Calendar endRangDate, OnTimeSelectListener selectListener) {
        boolean[] type = new boolean[]{true, true, true, true, false, false};
        return show(context, title, type, startRangDate, endRangDate, null, selectListener, null);
    }


    public static TimePickerView showTimeByH(Context context, String title, OnTimeSelectListener selectListener) {
        boolean[] type = new boolean[]{false, false, false, true, false, false};
        return show(context, title, type, null, null, null, selectListener, null);
    }

    /**
     * 显示 年月日时分秒的 时间控件
     *
     * @param context
     * @param startRangDate
     * @param endRangDate
     * @param selectListener
     * @param
     */

    public static TimePickerView showTimeByYMDHM(Context context, String title, Calendar startRangDate, Calendar endRangDate, OnTimeSelectListener selectListener) {
        boolean[] type = new boolean[]{true, true, true, true, true, false};
        return show(context, title, type, startRangDate, endRangDate, null, selectListener, null);
    }

    public static TimePickerView showTimeByYMDHM(Context context, String title, OnTimeSelectListener selectListener) {
        boolean[] type = new boolean[]{true, true, true, true, true, false};
        return show(context, title, type, null, null, null, selectListener, null);
    }

    public static TimePickerView showTimeByYMDHM(Context context, String title, Long selectTime, OnTimeSelectListener selectListener) {
        boolean[] type = new boolean[]{true, true, true, true, true, false};
        return show(context, title, type, null, null, selectTime, selectListener, null);
    }

    public static TimePickerView showTimeByYMDHM(Context context, String title, Long selectTime, OnTimeSelectListener selectListener,
                                                 View.OnClickListener cancelClickListener) {
        boolean[] type = new boolean[]{true, true, true, true, true, false};
        return show(context, title, type, null, null, selectTime, selectListener, cancelClickListener);
    }


    public static TimePickerView showTimeByYMDHMS(Context context, String title, Long selectTime, OnTimeSelectListener selectListener,
                                                  View.OnClickListener cancelClickListener) {
        boolean[] type = new boolean[]{true, true, true, true, true, true};
        return show(context, title, type, null, null, selectTime, selectListener, cancelClickListener);
    }

    public static TimePickerView show(Context context, String title, boolean[] type, Calendar startRangDate, Calendar endRangDate,
                                      Long selectedTime,
                                      OnTimeSelectListener selectListener, View.OnClickListener cancelClickListener) {

        Calendar selectedDate;
        if (selectedTime == null || selectedTime <= 0) {
            selectedDate = Calendar.getInstance();//系统当前时间
        } else {
            selectedDate = Calendar.getInstance();
            selectedDate.setTimeInMillis(selectedTime);
        }
        String titleString = "选择时间";
        if (!TextUtils.isEmpty(title)) {
            titleString = title;
        }
        TimePickerView pvTime;
        pvTime = new TimePickerBuilder(context, selectListener)
                .setType(type)
                .setDate(selectedDate)
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(cancelClickListener)
                .setItemVisibleCount(6) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText(titleString)
                .setTitleColor(context.getResources().getColor(R.color.pickerview_title_color))
                .setTitleSize(15)
                .setSubCalSize(18)
                .setSubmitColor(context.getResources().getColor(R.color.white))
                .setRangDate(startRangDate, endRangDate)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
        pvTime.show();
        return pvTime;
    }

    public static CalendarPicker showTimePicker(Activity context,Long startTime,Long endTime) {
        try{
            CalendarPicker picker = new CalendarPicker(context);
            picker.setHeight((int) (context.getResources().getDisplayMetrics().heightPixels * 0.65f));
            picker.setTitle("选择时间");
            picker.setIntervalNotes("开始", "结束");
            Date currentDate = new Date(System.currentTimeMillis());
            Calendar minCalendar = DateUtils.calendar(currentDate);
            minCalendar.add(Calendar.MONTH, -120);
            minCalendar.set(Calendar.DAY_OF_MONTH, DateUtils.maxDaysOfMonth(minCalendar.getTime()));
            Date minDate = minCalendar.getTime();

            Calendar maxCalendar = DateUtils.calendar(currentDate);
            maxCalendar.setTime(currentDate);
            maxCalendar.add(Calendar.MONTH, 120);
            maxCalendar.set(Calendar.DAY_OF_MONTH, DateUtils.maxDaysOfMonth(maxCalendar.getTime()));
            Date maxDate = maxCalendar.getTime();
            long currentTime=System.currentTimeMillis();
            if (startTime!=null && endTime!=null){
                currentTime=startTime;
                picker.setSelectedDate(startTime, endTime);
            }
            else {
                picker.setSelectedDate(currentTime, currentTime);
            }
            picker.setTitle(DateTimeUtils.formatDateTime(currentTime,DateTimeUtils.YM));
            picker.setRangeDate(minDate, maxDate);

            picker.getTitleView().setTextColor(context.getResources().getColor(R.color.color_black));
            picker.getTitleView().setTextSize(22);
           // CalendarView calendarView= picker.getCalendarView();
            picker.setColorScheme(new ColorScheme()
                    .daySelectBackgroundColor(context.getResources().getColor(R.color.color1_06AE56))
                    .dayStressTextColor(context.getResources().getColor(R.color.color1_06AE56)));
            picker.getCalendarView().getBodyView().addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);

                    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                    //判断是当前layoutManager是否为LinearLayoutManager
                    // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                    if (layoutManager instanceof LinearLayoutManager) {
                        LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                        //获取第一个可见view的位置
                        int firstItemPosition = linearManager.findFirstVisibleItemPosition();
                        Date date = picker.getCalendarView().getAdapter().getDateValue(firstItemPosition);
                        String time = DateTimeUtils.formatDateTime(date, DateTimeUtils.YM);
                        picker.setTitle(time);
                    }
                }
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                }
            });
            picker.show();
            return picker;
        }
        catch (Exception e){
            return null;
        }
    }

}
